package cn.iocoder.yudao.module.def.service.projectprogress;

import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.def.controller.admin.projectprogress.vo.*;
import cn.iocoder.yudao.module.def.dal.dataobject.projectprogress.ProjectProgressDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.def.dal.mysql.projectprogress.ProjectProgressMapper;

import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.module.def.enums.ErrorCodeConstants.*;

/**
 * 工程进度 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ProjectProgressServiceImpl implements ProjectProgressService {

    @Resource
    private ProjectProgressMapper projectProgressMapper;

    @Resource
    private AdminUserService userService;

    @Resource
    private DeptService deptService;

    @Override
    public Integer createProjectProgress(ProjectProgressSaveReqVO createReqVO) {

        // 插入
        ProjectProgressDO projectProgress = BeanUtils.toBean(createReqVO, ProjectProgressDO.class);
        projectProgressMapper.insert(projectProgress);
        // 返回
        return projectProgress.getId();
    }

    @Override
    public void updateProjectProgress(ProjectProgressSaveReqVO updateReqVO) {
        // 校验存在
        validateProjectProgressExists(updateReqVO.getId());
        // 更新
        ProjectProgressDO updateObj = BeanUtils.toBean(updateReqVO, ProjectProgressDO.class);
        projectProgressMapper.updateById(updateObj);
    }

    @Override
    public void deleteProjectProgress(Integer id) {
        // 校验存在
        validateProjectProgressExists(id);
        // 删除
        projectProgressMapper.deleteById(id);
    }

    private void validateProjectProgressExists(Integer id) {
        if (projectProgressMapper.selectById(id) == null) {
            throw exception(PROJECT_PROGRESS_NOT_EXISTS);
        }
    }

    @Override
    public ProjectProgressDO getProjectProgress(Integer id) {
        return projectProgressMapper.selectById(id);
    }

    @Override
    public PageResult<ProjectProgressDO> getProjectProgressPage(ProjectProgressPageReqVO pageReqVO) {

        LoginUser loginUser = getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());

        // 拼接数据
        DeptDO dept = deptService.getDept(user.getDeptId());
        String name = dept.getName();
        pageReqVO.setProjectNameAuth(name);
        return projectProgressMapper.selectPage(pageReqVO);
    }

    @Override
    public ProjectProgressDO getProjectProgressByPid(Integer id) {
        return projectProgressMapper.selectOne(new LambdaQueryWrapper<ProjectProgressDO>().eq(ProjectProgressDO::getProjectId,id));
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        projectProgressMapper.deleteByIds(ids);
    }

    @Override
    public ProjectProgressRespVO importUserList(List<ProjectProgressRespVO> list, Boolean updateSupport) {
        ProjectProgressRespVO result =  ProjectProgressRespVO.builder().build();
        // 1.1 参数校验
//        if (CollUtil.isEmpty(importUsers)) {
//            throw exception(USER_IMPORT_LIST_IS_EMPTY);
//        }
//        // 1.2 初始化密码不能为空
//        String initPassword = configApi.getConfigValueByKey(USER_INIT_PASSWORD_KEY);
//        if (StrUtil.isEmpty(initPassword)) {
//            throw exception(USER_IMPORT_INIT_PASSWORD);
//        }
//
//        // 2. 遍历，逐个创建 or 更新
//        UserImportRespVO respVO = UserImportRespVO.builder().createUsernames(new ArrayList<>())
//                .updateUsernames(new ArrayList<>()).failureUsernames(new LinkedHashMap<>()).build();
        list.forEach(importUser -> {
            // 2.1.1 校验字段是否符合要求
            try {
                ProjectProgressSaveReqVO bean = BeanUtils.toBean(importUser, ProjectProgressSaveReqVO.class);
                createProjectProgress(bean);
            } catch (ConstraintViolationException ex){
                return;
            }
            // 2.1.2 校验，判断是否有不符合的原因
          /*  try {
                validateUserForCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(),
                        importUser.getDeptId(), null);
            } catch (ServiceException ex) {
                respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage());
                return;
            }*/

            // 2.2.1 判断如果不存在，在进行插入
//            AdminUserDO existUser = userMapper.selectByUsername(importUser.getUsername());
//            if (existUser == null) {
//                userMapper.insert(BeanUtils.toBean(importUser, AdminUserDO.class)
//                        .setPassword(encodePassword(initPassword)).setPostIds(new HashSet<>())); // 设置默认密码及空岗位编号数组
//                respVO.getCreateUsernames().add(importUser.getUsername());
//                return;
//            }
            // 2.2.2 如果存在，判断是否允许更新
//            if (!isUpdateSupport) {
//                respVO.getFailureUsernames().put(importUser.getUsername(), USER_USERNAME_EXISTS.getMsg());
//                return;
//            }
//            AdminUserDO updateUser = BeanUtils.toBean(importUser, AdminUserDO.class);
//            updateUser.setId(existUser.getId());
//            userMapper.updateById(updateUser);
//            respVO.getUpdateUsernames().add(importUser.getUsername());
        });
        return result;
    }

    @Override
    public List<ProjectStatisticsExport> getAnnualStatistics() {
        return projectProgressMapper.getAnnualStatistics();
    }
}